package com.oxygen.pt.utils;


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oxygen.pt.pojo.dto.ChamberInspectionMonthlySaveDTO;
import com.oxygen.pt.pojo.dto.OxygenChamberInspectionSaveDTO;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 备注转化为字符串的工具类，方便进行
 */
public class InspectionRemarkConverter {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 把 DTO 中的零散备注字段合并成一条 JSON 字符串
     */
    public static String buildRemarksJson(ChamberInspectionMonthlySaveDTO dto) {
        Map<String, String> map = new LinkedHashMap<>();

        putIfNotBlank(map, "UPS", dto.getUpsRemark());
        putIfNotBlank(map, "observationWindow", dto.getObservationWindowRemark());
        putIfNotBlank(map, "pressureVessel", dto.getPressureVesselRemark());
        putIfNotBlank(map, "electricalSystem", dto.getElectricalSystemRemark());
        putIfNotBlank(map, "chamberDevice", dto.getChamberDeviceRemark());
        putIfNotBlank(map, "pressurePipe", dto.getPressurePipeRemark());
        putIfNotBlank(map, "emergencyDecompress", dto.getEmergencyDecompressRemark());
        putIfNotBlank(map, "fireSprinkler", dto.getFireSprinklerRemark());
        putIfNotBlank(map, "waterTank", dto.getWaterTankRemark());
        putIfNotBlank(map, "airCompressor", dto.getAirCompressorRemark());
        putIfNotBlank(map, "negativePump", dto.getNegativePumpRemark());
        putIfNotBlank(map, "containerWork", dto.getContainerWorkRemark());
        putIfNotBlank(map, "special", dto.getSpecialRemark());

        try {
            return MAPPER.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("JSON序列化失败", e);
        }
    }

    private static void putIfNotBlank(Map<String, String> map, String key, String value) {
        if (value != null && !value.isBlank()) {
            map.put(key, value);
        }
    }

    public static String extractMonthRemark(String json) {
        if (json == null || json.trim().isEmpty()) return "";
        try {
            Map<?,?> map = MAPPER.readValue(json, Map.class);
            return map.entrySet().stream()
                    .map(e -> e.getKey() + ":" + e.getValue())
                    .collect(Collectors.joining("；"));
        } catch (JsonProcessingException e) {
            return json;
        }
    }

    public static void fillRemarkFields(String json, ChamberInspectionMonthlySaveDTO dto) {
        if (StrUtil.isBlank(json)) return;
        try {
            Map<String, String> map = new Gson()
                    .fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
            dto.setUpsRemark(map.getOrDefault("UPS", ""));
            dto.setObservationWindowRemark(map.getOrDefault("observationWindow", ""));
            dto.setPressureVesselRemark(map.getOrDefault("pressureVessel", ""));
            dto.setElectricalSystemRemark(map.getOrDefault("electricalSystem", ""));
            dto.setChamberDeviceRemark(map.getOrDefault("chamberDevice", ""));
            dto.setPressurePipeRemark(map.getOrDefault("pressurePipe", ""));
            dto.setEmergencyDecompressRemark(map.getOrDefault("emergencyDecompress", ""));
            dto.setFireSprinklerRemark(map.getOrDefault("fireSprinkler", ""));
            dto.setWaterTankRemark(map.getOrDefault("waterTank", ""));
            dto.setAirCompressorRemark(map.getOrDefault("airCompressor", ""));
            dto.setNegativePumpRemark(map.getOrDefault("negativePump", ""));
            dto.setContainerWorkRemark(map.getOrDefault("containerWork", ""));
            dto.setSpecialRemark(map.getOrDefault("special", ""));
        } catch (Exception e) {
            // 解析失败可忽略或打日志
        }
    }

    /* ================= DTO -> JSON ================= */
    public static String buildRemarksJson(OxygenChamberInspectionSaveDTO dto) {
        Map<String, String> map = new LinkedHashMap<>();
        putIfNotBlank(map, "powerSupply", dto.getPowerSupplyRemark());
        putIfNotBlank(map, "computerSystem", dto.getComputerSystemRemark());
        putIfNotBlank(map, "lightingSystem", dto.getLightingSystemRemark());
        putIfNotBlank(map, "oxygenDevice", dto.getOxygenDeviceRemark());
        putIfNotBlank(map, "meterStatus", dto.getMeterStatusRemark());
        putIfNotBlank(map, "flowSwitch", dto.getFlowSwitchRemark());
        putIfNotBlank(map, "electricParts", dto.getElectricPartsRemark());
        try {
            return MAPPER.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("JSON序列化失败", e);
        }
    }

    /* ================= JSON -> DTO ================= */
    public static void fillRemarkFields(String json, OxygenChamberInspectionSaveDTO dto) {
        if (StrUtil.isBlank(json)) return;
        try {
            Map<String, String> map = new Gson()
                    .fromJson(json, new com.google.gson.reflect.TypeToken<Map<String, String>>(){}.getType());
            dto.setPowerSupplyRemark(map.getOrDefault("powerSupply", ""));
            dto.setComputerSystemRemark(map.getOrDefault("computerSystem", ""));
            dto.setLightingSystemRemark(map.getOrDefault("lightingSystem", ""));
            dto.setOxygenDeviceRemark(map.getOrDefault("oxygenDevice", ""));
            dto.setMeterStatusRemark(map.getOrDefault("meterStatus", ""));
            dto.setFlowSwitchRemark(map.getOrDefault("flowSwitch", ""));
            dto.setElectricPartsRemark(map.getOrDefault("electricParts", ""));
        } catch (Exception e) {
            // 解析失败可记录日志或直接跳过
        }
    }

}